<script setup lang="ts">
import { postLoginAPI, postLoginWxMinAPI, postLoginWxMinSimpleAPI } from '@/services/login.ts'
import { useMemberStore } from '@/stores'
import type { LoginResult } from '@/types/member'
import { ref, defineProps, onMounted, watch, defineEmits } from 'vue'

// 状态管理
const memberStore = useMemberStore()
const isAgreePrivacy = ref(false)
const isAgreePrivacyShakeY = ref(false)
const query = defineProps<{
  isLogin: boolean
  isPopupVisible: boolean
}>()
const emit = defineEmits(['update:isPopupVisible'])

// #ifdef MP-WEIXIN
let code = ''

uni.login({
  success(res) {
    code = res.code
  },
})
onMounted(() => {
  localisPopupVisible.value = query.isPopupVisible
})

// 同步父组件状态变化
watch(
  () => query.isPopupVisible,
  (newVal) => {
    localisPopupVisible.value = newVal
  },
)
// 获取用户手机号码
const onGetphonenumber = async (ev: UniHelper.ButtonOnGetphonenumber) => {
  await checkedAgreePrivacy()
  const { encryptedData, iv } = ev.detail
  const res = await postLoginWxMinAPI({ code, encryptedData, iv })
  loginSuccess(res.data)
}
// #endif

// 模拟手机号码快捷登录（开发练习）
const onGetphonenumberSimple = async () => {
  await checkedAgreePrivacy()
  const res = await postLoginWxMinSimpleAPI('13123456789')
  loginSuccess(res.data)
}

// 登录成功处理
const loginSuccess = (profile: LoginResult) => {
  memberStore.setProfile(profile)
  uni.showToast({ icon: 'success', title: '登录成功' })
  //关闭弹窗
  localisPopupVisible.value = true
}

// 表单数据（H5 使用）
const form = ref({
  account: '13123456789',
  password: '',
})

// 表单提交（H5 使用）
const onSubmit = async () => {
  await checkedAgreePrivacy()
  const res = await postLoginAPI(form.value)
  loginSuccess(res.data)
}

// 验证是否勾选协议
const checkedAgreePrivacy = async () => {
  if (!isAgreePrivacy.value) {
    uni.showToast({
      icon: 'none',
      title: '请先阅读并勾选协议',
    })
    isAgreePrivacyShakeY.value = true
    setTimeout(() => {
      isAgreePrivacyShakeY.value = false
    }, 500)
    return Promise.reject(new Error('请先阅读并勾选协议'))
  }
}

// 打开隐私协议
const onOpenPrivacyContract = () => {
  // #ifdef MP-WEIXIN
  wx.openPrivacyContract({})
  // #endif
}

// 弹窗状态
const localisPopupVisible = ref<boolean>()

// // 打开弹窗
// const openPopup = () => {
//   isPopupVisible.value = true
// }
const closePopup = () => {
  emit('update:isPopupVisible', true)
  localisPopupVisible.value = true
}
</script>
<template>
  <view class="container" v-if="query.isLogin">
    <!-- 底部弹出框 -->
    <view v-if="!localisPopupVisible" class="popup-container">
      <view class="popup-content">
        <view class="popup-header">
          <text class="title">登录</text>
          <text class="close-icon" @tap="closePopup">×</text>
        </view>

        <!-- 登录方式 -->
        <view class="login-methods">
          <!-- 小程序端授权登录 -->
          <!-- #ifdef MP-WEIXIN -->
          <button class="phone-login" open-type="getPhoneNumber" @getphonenumber="onGetphonenumber">
            <text class="icon icon-phone"></text>
            手机号快捷登录
          </button>
          <!-- #endif -->

          <!-- H5 表单登录 -->
          <!-- #ifdef H5 -->
          <input
            v-model="form.account"
            class="input"
            type="text"
            placeholder="请输入用户名/手机号码"
          />
          <input
            v-model="form.password"
            class="input"
            type="text"
            password
            placeholder="请输入密码"
          />
          <button @tap="onSubmit" class="button phone">登录</button>
          <!-- #endif -->

          <!-- 模拟快捷登录 -->
          <button @tap="onGetphonenumberSimple" class="simulate-login">
            <text class="icon icon-phone">模拟快捷登录</text>
          </button>
        </view>

        <!-- 协议勾选 -->
        <view class="tips" :class="{ animate__shakeY: isAgreePrivacyShakeY }">
          <label class="label" @tap="isAgreePrivacy = !isAgreePrivacy">
            <radio class="radio" color="#28bb9c" :checked="isAgreePrivacy" />
            <text>登录/注册即视为你同意Ai助手</text>
          </label>

          <text class="link" @tap="onOpenPrivacyContract">《隐私协议》</text>
        </view>
      </view>
    </view>
  </view>
</template>
<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.content {
  text-align: center;

  .logo {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 40rpx;
  }

  .login-button {
    width: 80%;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 32rpx;
    color: #fff;
    background-color: #28bb9c;
    border-radius: 40rpx;
  }
}

.popup-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 999;
  animation: slide-up 0.3s ease-in-out;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;

  .title {
    font-size: 36rpx;
    font-weight: bold;
  }

  .close-icon {
    font-size: 40rpx;
    color: #999;
  }
}

.login-methods {
  display: flex;
  flex-direction: column;
  gap: 20rpx;

  .phone-login,
  .simulate-login {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 80rpx;
    font-size: 28rpx;
    color: #fff;
    background-color: #28bb9c;
    border-radius: 40rpx;
  }

  .input {
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border: 1px solid #ddd;
    border-radius: 40rpx;
    padding: 0 20rpx;
    margin-bottom: 20rpx;
  }
}

.tips {
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #999;
  text-align: center;

  .radio {
    transform: scale(0.7);
    margin-right: 10rpx;
  }

  .link {
    color: #28bb9c;
  }
}

@keyframes slide-up {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.animate__shakeY {
  animation: shakeY 0.2s ease-in-out 3;
}

@keyframes shakeY {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10rpx);
  }
  100% {
    transform: translateY(0);
  }
}
</style>
